//
// Created by yyancy on 2019/10/31.
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

void error_handling(char *string);

#define SA struct sockaddr *


int server() {
    struct sockaddr_in server_sock;
    struct sockaddr_in client_sock;
    int server_fd;
    int client_fd;
    socklen_t clien_sock_len;
    char buf[100];
    char *mes = "hello,world";

    server_sock.sin_family = PF_INET;
    server_sock.sin_addr.s_addr = htonl(INADDR_ANY);
//    server_sock.sin_addr.s_addr = inet_addr("127.0.0.1");
    server_sock.sin_port = htons(8080);

    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        error_handling("socket() error");
    }

    if (bind(server_fd, (SA) &server_sock, sizeof(server_sock)) == -1) {
        error_handling("bind() error");
    }

    if (listen(server_fd, 4) == -1) {
        error_handling("listen() error");
    }


    for (int i = 0; i < 5; ++i) {
        clien_sock_len = sizeof(client_sock);
        if ((client_fd = accept(server_fd, (SA) &client_sock, &clien_sock_len)) == -1) {
            error_handling("accept() error");
        }
        ssize_t n;
        int body[100];
        int cnt, oper;
        n = read(client_fd, &cnt, 4);
        read(client_fd, body, cnt * 4);
        read(client_fd, &oper, 4);
        int result = body[0];
        switch (oper) {
            case '+':
                for (int j = 1; j < cnt; ++j) {
                    result += body[j];
                }
                break;
            case '-':
                for (int j = 1; j < cnt; ++j) {
                    result -= body[j];
                }
                break;
            case '*':
                for (int j = 1; j < cnt; ++j) {
                    result *= body[j];
                }
                break;
            case '/':
                for (int j = 1; j < cnt; ++j) {
                    result /= body[j];
                }
                break;
        }
        printf("result=  %d \n", result);
        write(client_fd, &result, 4);

    }

    close(client_fd);
    close(server_fd);

    return 0;
}

void error_handling(char *string) {
    fputs(string, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main() {
    server();
    return 0;
}